package com.taotao.zerocopy;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Description: NIO 的零拷贝实现 IO传输，耗时测试
 * @Author: TaoJF
 * @Date: Created in 2018/7/8 下午3:33
 */
public class NewIOServer {

    public static void main(String[] args) throws IOException {
        InetSocketAddress address = new InetSocketAddress(8088);

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        ServerSocket serverSocket = serverSocketChannel.socket();
        serverSocket.setReuseAddress(true);
        serverSocket.bind(address);
        System.out.println("服务器端启动监听...");

        ByteBuffer byteBuffer = ByteBuffer.allocate(4069);

        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            System.out.println("监听到，进行处理...");
            socketChannel.configureBlocking(true);

            int readCount = 0;
            int totalReadCount = 0;

            while (readCount >= 0) {
                readCount = socketChannel.read(byteBuffer);
                if (readCount >= 0) {
                    totalReadCount += readCount;
                }
                byteBuffer.rewind();
            }
            System.out.println("读取到的字节长度：" + totalReadCount);
        }
    }

}
